/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.ComponentModel;
using System.Windows.Forms;
using TeachMe.Application.Events;
using TeachMe.Application.Properties;

namespace TeachMe.Application.Controls
{
    public abstract class ErrorEdit : TextBox
    {
        private string _errorText;
        private ErrorProvider _errorProvider;
        public event EventHandler<ValidatingEventArgs> ValidatingValue;

        [Browsable(true)]
        public string ErrorText
        {
            get { return _errorText; }
            set { _errorText = value; }
        }

        public bool IsValid()
        {
            return InternalIsValid() && FireValidatingValue();
        }

        protected override void OnTextChanged(EventArgs e)
        {
            UpdateErrorProvider(!IsValid());

            base.OnTextChanged(e);
        }

        protected abstract bool InternalIsValid();

        private void UpdateErrorProvider(bool visible)
        {
            if (!visible && _errorProvider == null)
            {
                return;
            }

            if (_errorProvider == null)
            {
                _errorProvider = new ErrorProvider();
                _errorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink;
            }

            if (visible)
            {
                _errorProvider.SetIconAlignment(this, ErrorIconAlignment.MiddleRight);
                _errorProvider.SetIconPadding(this, 2);
                _errorProvider.SetError(this, String.IsNullOrEmpty(ErrorText) ? Resources.StrictEditInvalidValue : ErrorText);
            }
            else
            {
                _errorProvider.Clear();
            }
        }

        private bool FireValidatingValue()
        {
            EventHandler<ValidatingEventArgs> handler = ValidatingValue;
            if (handler != null)
            {
                ValidatingEventArgs eventArgs = new ValidatingEventArgs { Valid = true };
                handler(this, eventArgs);
                return eventArgs.Valid;
            }

            return true;
        }
    }
}
